package cn.edu.zut.hkxy.service.impl;

import cn.edu.zut.hkxy.mapper.DocsMapper;
import cn.edu.zut.hkxy.pojo.Docs;
import cn.edu.zut.hkxy.pojo.DocsExample;
import cn.edu.zut.hkxy.service.DocsService;
import cn.edu.zut.hkxy.util.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Service
@Transactional
public class DocsServiceImpl implements DocsService {

    @Autowired
    private DocsMapper docsMapper;

    @Override
    public boolean addOne(Docs docs,MultipartFile file) throws IOException {
        String name=file.getOriginalFilename();
        if(name==null||name.equals("")){

        }else{
            Map<String,String> map=FileUploadUtils.saveDocsGetPath(file);
            String url=map.get("url");
            String path=map.get("path");
            docs.setUrl(url);
            docs.setPath(path);
            docs.setTitle(name);
        }
        docs.setDate(new Date());
        docsMapper.insert(docs);
        return false;
    }

    @Override
    public boolean addBatch(int download_id,MultipartFile[] files) throws IOException {
        List<Docs> docsList=new ArrayList<>();
        for(MultipartFile file:files) {
            Docs docs=new Docs();
            String title=file.getOriginalFilename();
            docs.setTitle(title);
            Map<String,String> map=FileUploadUtils.saveDocsGetPath(file);
            docs.setPath(map.get("path"));
            docs.setUrl(map.get("url"));
            docs.setDownloadsId(download_id);
            docs.setDate(new Date());
            docsList.add(docs);
            System.out.println(docs);
        }
        System.out.println(docsList.size());
        int i=docsMapper.insertBatch(docsList);
        if(i>=1){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean deleteOne(Integer id) {
        return false;
    }

    @Override
    public boolean deleteDownloadDocsBatch(Integer downloads_id) {
        DocsExample example =new DocsExample();
        example.createCriteria().andDownloadsIdEqualTo(downloads_id);
        int i=docsMapper.deleteByExample(example);
        if(i>=1){
            return true;
        }else {
            return false;
        }
    }
}
